package top.kaoshanji.p3ch13a;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import top.kaoshanji.u1constant.FileConstant;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * 代码清单-p3ch13a-426页a：对称加密和解密操作的示例
 * author kaoshanji
 * ^_^
 * create time 2025/2/8 16:59
 */
public class SymmetricEncryption {

    private static final Logger logger = LogManager.getLogger(SymmetricEncryption.class);

    private final String ROOT_PATH = FileConstant.LOCAL_ROOT_PATH.concat("p3ch13a426页a\\");

    public static void main(String[] args) throws Exception {
        logger.info("...代码清单-p3ch13a-426页a：对称加密和解密操作的示例...");

        SymmetricEncryption se = new SymmetricEncryption();
        se.encrypt();
        se.decrypt();
    }

    /**
     * 加密
     */
    public void encrypt() throws Exception {
        KeyGenerator generator = KeyGenerator.getInstance("DES");
        SecretKey key = generator.generateKey();

        Files.write(Paths.get(ROOT_PATH.concat("key.data")), key.getEncoded());

        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.ENCRYPT_MODE, key);

        String text = "Hello World";

        byte[] encrypted = cipher.doFinal(text.getBytes());
        Files.write(Paths.get(ROOT_PATH.concat("encrypted.bin")), encrypted);
    }

    /**
     * 解密
     */
    public void decrypt() throws Exception {
        byte[] keyData = Files.readAllBytes(Paths.get(ROOT_PATH.concat("key.data")));

        SecretKeySpec keySpec = new SecretKeySpec(keyData, "DES");
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec);

        byte[] data = Files.readAllBytes(Paths.get(ROOT_PATH.concat("encrypted.bin")));
        byte[] result = cipher.doFinal(data);

        String str = new String(result);

        logger.info("...解密的明文：{}...", str);
    }



}
